<!-- 单位设计师任务列表 -->
<template>
    <search-table
        :columns="columns"
        :data="taskData"
        :total="taskTotal"
        :page.sync="query.pageIndex"
        :size.sync="query.pageSize"
        @queryFun="queryUserTask"
    >
        <template slot="input-group">
            <Input v-model="query.taskName" placeholder="任务名称" @on-change="debounceSearch" clearable />
        </template>
        <DrawerPage v-model="reportModal.show" :title="reportModal.title" width="1000">
            <Summary :props="$props" :taskId="reportModal.taskId" :taskStatus="reportModal.taskStatus" v-if="reportModal.show"></Summary>
        </DrawerPage>
        <Modal v-model="vmModal.show" :title="vmModal.title" :width="1000">
            <TableList :columns="vmCol" :data="deviceList"></TableList>
        </Modal>
        <DetailModal ref="detailModal" :columns="columns"></DetailModal>
    </search-table>
</template>

<script>
import {
    queryUserTask,
    startTask
} from '../../api/task';
import {
    getvmInfo
} from '@/api/drill_compete';
import { queryVmStatus, opVms, rebuildVm, rebootVm } from '@/api/remote'
import { mapState, mapMutations } from 'vuex';
import { debounce } from '@/libs/utils';
import Summary from '../summary'
import DetailModal from '../../detail';
export default {
    name: 'scenes',
    inject: ['detailParent'],
    components: {
        Summary,
        DetailModal
    },
    props: {
        disabledAllBtn:{
            type:Boolean,
            default:false
        },
        contentId:{
            type:String,
            default:''
        },
        projectId:{
            type:String,
            default:''
        },
    },
    mixins: [],
    data() {
        return {
            taskData:[],
            taskTotal:0,
            query:{
                contentId:this.contentId,
                projectId:this.projectId,
                pageIndex:1,
                pageSize:10
            },
            columns: [
                {
                    type:'link',
                    title: '名称',
                    key: 'taskName',
                    align: 'center',
                    width: 230,
                    placement: 'top-left',
                    order: 1,
                    tooltip: true,
                    fun:(data) => {
                        this.$refs.detailModal.showModal(data,data.taskName)
                    }
                },
                {
                    title: '状态',
                    key: 'status',
                    filter:(status) => {
                        return status === 0 ? '未开始' : status === 1 ? '已完成' : '进行中'
                    },
                    setColor: (status) => {
                        return status === 0 ? 'var(--status-pre)' : status === 1 ? 'var(--status-yes)' : 'var(--status-ing)'
                    },
                },
                {
                    type:'link',
                    title: '设备',
                    key: 'deviceTOList',
                    align: 'center',
                    minWidth:140,
                    filter:(deviceTOList) => deviceTOList.map(item => item.deviceName).join(','),
                    tooltip: true,
                    fun:(data) => {
                        let deviceList = data.deviceTOList;
                        let pArr = deviceList.map(item => {
                            return this.getVmBaseInfo(item)
                        })
                        this.vmModal.show = true
                        Promise.all(pArr).then(() => {
                            this.deviceList = deviceList.filter(item => item.name);
                            this.reachManyVmStatus()
                        })
                    }
                },
                {
                    title:'描述',
                    key: 'description',
                    tooltip: true
                },
                {
                    key:"startTime",
                    title:'开始时间',
                    tooltip:true,
                    show:false
                },
                {
                    key:"endTime",
                    title:'截止时间',
                    tooltip:true,
                    show:false
                },
                {
                    key:"realTime",
                    title:'实际开始时间',
                    tooltip:true
                },
                {
                    key:"finishTime",
                    title:'完成时间',
                    tooltip:true
                },
                {
                    title: '创建者',
                    key: 'creatorName',
                    align: 'center',
                    width: 120,
                    tooltip: true,
                },
                {
                    title: '创建时间',
                    key: 'createTime',
                    align: 'center',
                    minWidth:140,
                },
                {
                    title: '操作',
                    width: 250,
                    key: 'action',
                    opList: [
                        {
                            txt: '开始任务',
                            tooltip: true,
                            title: '确认开始任务？',
                            disabled: (data) => {
                                return data.status !== 0;
                            },
                            fun: this.startTask
                        },
                        {
                            txt: '上传科研文档',
                            disabled: (data) => {
                                return data.status === 0;
                            },
                            fun: (data) => {
                                this.reportModal.show = true;
                                this.reportModal.taskId = data.id;
                                this.reportModal.taskStatus = data.status;
                            }
                        }
                    ]
                }
            ],
            reportModal:{
                show:false,
                title:'上传科研文档'
            },
            vmModal:{
                show:false,
                title:'虚拟机详情',
                data:{}
            },
            vmGroupStatus: [],
            deviceList:[],
            vmCol: [
                {
                    title: '虚拟机名称',
                    key: 'name',
                    minWidth: 50,
                    tooltip: true,
                },
                {
                    title: 'IP',
                    key: 'ipAddress',
                    minWidth: 50,
                    tooltip: true,
                    render: (h, params) => {
                        let _this = this;
                        params = params.row;
                        let addresses = [];
                        if (params.addresses) {
                            if (params.addresses.length != 0) {
                                addresses = params.addresses.map((item) => {
                                    //                                          return h('div',{},item.ip);
                                    let ips = item.ips.map((ip) => {
                                        return h('div', {}, ip.ipAddress);
                                    });
                                    return h('div', {}, ips);
                                });
                                return h('div', {}, addresses);
                            }
                        }
                    },
                },
                {
                    title: '用户名',
                    key: 'username',
                    minWidth: 50,
                    tooltip: true,
                    filter: (accesses, data) => {
                        return data.accesses.length > 0 ? data.accesses[0].username : '-';
                    },
                },
                {
                    title: '密码',
                    key: 'password',
                    minWidth: 50,
                    tooltip: true,
                    filter: (accesses, data) => {
                        return data.accesses.length > 0 ? data.accesses[0].password : '-';
                    },
                },
                // {
                //     title: '接入类型',
                //     key: 'accessType',
                //     minWidth: 50,
                //     tooltip: true,
                //     filter: (accesses, data) => {
                //         return data.accesses.length > 0
                //             ? data.accesses.map((item) => item.accessType).join(',')
                //             : '-';
                //     },
                // },
                {
                    title: '操作系统类型',
                    key: 'sysType',
                    minWidth: 50,
                    tooltip: true,
                },
                // {
                //     title: '镜像名称',
                //     key: 'imageName',
                //     minWidth: 50,
                //     tooltip: true,
                // },
                {
                    title: '虚拟机状态',
                    key: 'status',
                    minWidth: 100,
                    render: (h, params) => {
                        let _this = this;
                        params = params.row;
                        let statusVm = '',
                            fontColor = '',
                            statusLoading = false,
                            ErrorMesage = '';
                        if (_this.vmGroupStatus.length != 0) {
                            _this.vmGroupStatus.forEach((element) => {
                                if (element.id == params.id) {
                                    if (element.enableCrash) {
                                        statusVm = 'MELT';
                                        ErrorMesage = element.crashMsg;
                                    } else {
                                        statusVm = element.status;
                                        ErrorMesage = '';
                                        // statusVm  =  "MELT";
                                    }
                                    statusLoading = element.loading;
                                    return;
                                }
                            });
                        }
                        let statusVmGroup = {
                            ACTIVE: '运行中/#43CD80/false/alRunning.png',
                            Running: '运行中/#43CD80/false/alRunning.png',
                            SHUTOFF: '已关机/#DB4747/false/alOff.png',
                            DOWN: '已关机/#DB4747/false/alOff.png',
                            Stopped: '已停止/#DB4747/false/alStop.png',
                            SUSPENDED: '已挂起/#DB4747/false/alSuspend.png',
                            ERROR: '运行ERROR/#DB4747/false/runningError.png',
                            PAUSED: '已暂停/#43CD80/false/alPause.png',
                            CRUSH: '运行ERROR/#DB4747/false/runningError.png',
                            UNKNOWN: '运行ERROR/#DB4747/false/runningError.png',
                            'powering-off': '关机中/#57a3f3/true',
                            'powering-on': '启动中/#57a3f3/true',
                            rebuilding: '重置中/#57a3f3/true',
                            rebooting_hard: '重启中/#57a3f3/true',
                            suspending: '挂起中/#57a3f3/true',
                            resuming: '拯救中/#57a3f3/true',
                            pausing: '暂停中/#57a3f3/true',
                            unpausing: '启动中/#57a3f3/true',
                            MELT: '已崩溃/#DB4747/false/runningError.png',
                        };
                        if (!statusVmGroup[statusVm]) {
                            statusVmGroup[statusVm] = '进行中/#43CD80/true';
                        }
                        let _iamgeName =
                            statusVmGroup[statusVm].split('/')[2] == 'false'
                                ? './static/' + statusVmGroup[statusVm].split('/')[3]
                                : '';
                        return h(
                            'div',
                            {
                                style: {
                                    color: statusVmGroup[statusVm].split('/')[1],
                                },
                            },
                            [
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            loading:
                                                statusVmGroup[statusVm].split('/')[2] == 'false'
                                                    ? false
                                                    : true,
                                        },
                                        attrs: {
                                            title: ErrorMesage,
                                        },
                                        class: 'status-loading',
                                        style: {
                                            background: 'none!important',
                                            padding: 0,
                                            border: 'none!important',
                                        },
                                    },
                                    [
                                        h(
                                            'span',
                                            {
                                                style: {
                                                    color: statusVmGroup[statusVm].split('/')[1],
                                                },
                                            },
                                            statusVmGroup[statusVm].split('/')[0]
                                        ),
                                    ]
                                ),
                            ]
                        );
                    },
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 260,
                    opList: [
                        // {
                        //     txt: '生成镜像',
                        //     tooltip: true,
                        //     title: '确定生成镜像？',
                        //     disEdit: (data) => {
                        //         let statusVm,
                        //             _this = this;
                        //         if (_this.vmGroupStatus.length != 0) {
                        //             _this.vmGroupStatus.forEach((element) => {
                        //                 if (element.id == data.id) {
                        //                     if (element.enableCrash) {
                        //                         statusVm = 'MELT';
                        //                     } else {
                        //                         statusVm = element.status;
                        //                     }
                        //                 }
                        //             });
                        //         }
                        //         let disabled =
                        //             !(statusVm == 'DOWN' || statusVm == 'SHUTOFF') ||
                        //             data.vzType == 'docker';
                        //         return disabled;
                        //     },
                        //     fun: (data) => {
                        //         this.createImage(data);
                        //         return;
                        //         this.curVm = data;
                        //         this.createImageModal.show = true;
                        //     },
                        // },
                        {
                            txt: '开机',
                            tooltip: true,
                            title: '确认对该虚拟机进行开机操作吗?',
                            disEdit: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    _this.vmGroupStatus.forEach((element, i) => {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled = !['SHUTOFF', 'DOWN', 'Stopped'].includes(statusVm);
                                return disabled;
                            },
                            fun: (data) => {
                                this.vmSwitchTypeOp(data.id, '开机');
                            },
                        },
                        {
                            txt: '关机',
                            tooltip: true,
                            title: '确认对该虚拟机进行关机操作吗?',
                            disEdit: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    _this.vmGroupStatus.forEach((element) => {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled = !['Running', 'ACTIVE', 'CRUSH', 'PASSWORD'].includes(
                                    statusVm
                                );
                                return disabled;
                            },
                            fun: (data) => {
                                this.vmSwitchTypeOp(data.id, '关机');
                            },
                        },
                        {
                            txt: '重置',
                            tooltip: true,
                            title: '确认对该虚拟机进行重置操作吗',
                            disEdit: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    _this.vmGroupStatus.forEach((element, i) => {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled = [
                                    'SUSPENDED',
                                    'ERROR',
                                    'PASSWORD',
                                    'CRUSH',
                                    'PASSWORD',
                                ].includes(statusVm);
                                return disabled;
                            },
                            fun: (data) => {
                                this.vmSwitchTypeOp(data.id, '重置');
                            },
                        },
                        {
                            txt: '重启',
                            tooltip: true,
                            title: '确认对该虚拟机进行重启操作吗?',
                            disEdit: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    _this.vmGroupStatus.forEach((element, i) => {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled = !['ACTIVE', 'Running', 'CRUSH', 'MELT'].includes(
                                    statusVm
                                );
                                return disabled;
                            },
                            fun: (data) => {
                                this.vmSwitchTypeOp(data.id, '重启');
                            },
                        },
                        // {
                        //     txt: '工具库',
                        //     disEdit: (data) => {
                        //         let statusVm,
                        //             _this = this;
                        //         if (_this.vmGroupStatus.length != 0) {
                        //             _this.vmGroupStatus.forEach((element) => {
                        //                 if (element.id == data.id) {
                        //                     if (element.enableCrash) {
                        //                         statusVm = 'MELT';
                        //                     } else {
                        //                         statusVm = element.status;
                        //                     }
                        //                 }
                        //             });
                        //         }
                        //         let disabled = !['Running', 'ACTIVE'].includes(
                        //             statusVm
                        //         );
                        //         return disabled;
                        //     },
                        //     fun: (vm) => {
                        //         let currentSubnetId = vm.addresses[0].ips[0].subnetId;
                        //         // this.$refs.toolModal.showModal(currentSubnetId);
                        //         // this.toolModal.show = true;
                        //         // // this.curVm = vm;
                        //         // this.currentSubnetId = vm.addresses[0].ips[0].subnetId;
                        //         // this.getToolTunnelDetail();
                        //     }
                        // },
                        {
                            txt: '进入虚拟机',
                            dropdown: true,
                            dropdownList: (data) => {
                                let accessType = [
                                    ...new Set(['console',...data.accesses.map((access) => access.accessType)]),
                                ].map((access) => {
                                    return {
                                        name: access,
                                        title: access,
                                    };
                                });
                                return accessType;
                            },
                            // current: (data) => {
                            //     return {
                            //         name: data.accesses[0].accessType,
                            //         title: data.accesses[0].accessType
                            //     };
                            // },
                            disEdit: (data) => {
                                let statusVm,
                                    _this = this;
                                if (_this.vmGroupStatus.length != 0) {
                                    _this.vmGroupStatus.forEach((element, i) => {
                                        if (element.id == data.id) {
                                            if (element.enableCrash) {
                                                statusVm = 'MELT';
                                            } else {
                                                statusVm = element.status;
                                            }
                                        }
                                    });
                                }
                                let disabled = !['ACTIVE', 'Running'].includes(statusVm);
                                return disabled;
                            },
                            fun: (data, type) => {
                                let href = this.$router.resolve({
                                    name:'toolMachine',
                                    query:{
                                        prjId:this.prjId,
                                        currentSubnetId:data.addresses[0].ips[0].subnetId,
                                        vmName:data.name,
                                        vmId:data.id,
                                        type:type || data.accesses[0].accessType,
                                        useIn:data.name === this.accessName ? 'newTools' : ''
                                    }
                                }).href;
                                window.openTrain(href, '_blank');
                                // this.$router.push({
                                //     name:'toolMachine',
                                //     query:{
                                //         prjId:this.prjId,
                                //         currentSubnetId:data.addresses[0].ips[0].subnetId,
                                //         vmName:data.name,
                                //         vmId:data.id,
                                //         type:type || data.accesses[0].accessType
                                //     }
                                // })
                                // this.vmAccess(data.id, type || data.accesses[0].accessType);
                            },
                        },
                        // {
                        //     txt: '设为接入机器',
                        //     fun: (vm) => {
                        //         //设为接入机器
                        //         updateContent(this.ecId, { accessName: vm.name }).then(
                        //             ({ code, data, message }) => {
                        //                 if (code === 1) {
                        //                     this.$Message.info('设置成功');
                        //                     this.detailParent.contentDetail.accessName = vm.name;
                        //                 } else {
                        //                     this.$Message.error(message);
                        //                 }
                        //             }
                        //         );
                        //     }
                        // }
                    ],
                },
            ]
        };
    },
    filters: {},
    computed: {
        ...mapState('user', ['nickname', 'userId', 'isRootDesigner']),
        accessName() {
            return this.detailParent.contentDetail.accessName;
        },
    },
    watch:{
        
    },
    mounted() {
        this.queryUserTask()
    },
    methods: {
        queryUserTask(){
            queryUserTask({...this.query,userId:this.userId}).then(({code,data}) => {
                if(code === 1){
                    this.taskData = data.items;
                    this.taskTotal = data.total;
                }else{
                    this.taskData = [];
                    this.taskTotal = 0;
                }
            })
        },
        startTask(task){
            startTask(task.id).then(({code}) => {
                if(code === 1){
                    this.queryUserTask()
                }
            })
        },
        // 防抖封装
        debounceSearch: debounce(function () {
            this.query.pageIndex = 1;
            this.queryUserTask()
        }),
        getVmBaseInfo(host, enableRecordScreen) {
            return new Promise((resolve,reject) => {
                getvmInfo(host.deviceId).then((res) => {
                    if (res.code === 1) {
                        Object.assign(host,res.data);
                        resolve(res.data)
                    }
                });
            })
        },
        gotoVm(access){
            let href = this.$router.resolve({
                name:'toolMachine',
                query:{
                    prjId:this.projectId,
                    currentSubnetId:this.vmModal.data.addresses[0].ips[0].subnetId,
                    vmName:this.vmModal.data.name,
                    vmId:this.vmModal.data.id,
                    type:access.accessType,
                    useIn:'newTools'
                }
            }).href;
            window.openTrain(href, '_blank');  
        },
        //批量查询虚拟机状态
        reachManyVmStatus() {
            let vmIdGroup = this.deviceList.map(vm => vm.deviceId);
            queryVmStatus(vmIdGroup).then( response => {
                if (response.code == 1) {
                    let status_null = [];
                    let vm_status = '',
                        vm_loading = false;
                    this.vmGroupStatus = response.list.map((item) => {
                        if (item.taskStatus != 'null') {
                            status_null.push(item.vmId);
                            vm_status = item.taskStatus;
                            vm_loading = true;
                        } else {
                            vm_status = item.status;
                            vm_loading = false;
                        }
                        return {
                            id: item.vmId,
                            status: vm_status,
                            loading: vm_loading,
                            enableCrash: item.enableCrash,
                            crashMsg: item.crashMsg ? item.crashMsg : '',
                        };
                    });
                    if (status_null.length != 0 && this.vmModal.show) {
                        setTimeout(() => {
                            this.reachManyVmStatus()
                        },5000)
                    }
                } else {
                    this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        vmSwitchTypeOp(id, type) {
            let vmId = id || this.opVm.id;
            let text = type || this.opVmType;
            let batch = '';
            let _this = this;
            switch (text) {
                case '关机':
                    _this.operationVm(vmId, 'stop', batch);
                    break;
                case '开机':
                    _this.operationVm(vmId, 'start', batch);
                    break;
                case '重置状态':
                    _this.operationVm(vmId, 'reset-state-active', batch);
                    break;
                case '重启':
                    _this.rebootVm(vmId, batch);
                    break;
                case '重置':
                    _this.rebuildVm(vmId, batch);
                    break;
                case '挂起':
                    _this.operationVm(vmId, 'suspend', batch);
                    break;
                case '暂停':
                    _this.operationVm(vmId, 'pause', batch);
                    break;
                case '拯救':
                    _this.operationVm(vmId, 'resume', batch);
                    break;
                case '取消暂停':
                    _this.operationVm(vmId, 'unpause', batch);
                    break;
            }
        },
        //操作网络
        operationVm(vmId, action, batch) {
            opVms(vmId,action).then((response) => {
                if (response.code == 1) {
                    this.$Message.info('操作成功');
                    this.reachManyVmStatus()
                } else {
                    this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        //重置
        rebuildVm(vmId, batch) {
            rebuildVm(vmId).then((response) => {
                if (response.code == 1) {
                    this.$Message.info('操作成功');
                    this.reachManyVmStatus()
                } else {
                    this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        //重启
        rebootVm(vmId, batch) {
            rebootVm(vmId).then(response => {
                if (response.code == 1) {
                    this.$Message.info('操作成功');
                    this.reachManyVmStatus()
                } else {
                    this.$Message.error({
                        content: response.prompt,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
    }
};
</script>

<style scoped>
.status-loading.ivu-btn:before {
    background: none;
}
.status-loading .ivu-load-loop {
    font-weight: bold;
    /* color: var(--table-tr-color); */
    color: #999;
}
</style>
